package edu.example.house.serlvet;

import edu.example.bean.buildings;
import edu.example.common.PowerCheck;
import edu.example.house.dao.housemanageDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/buildingUpdate")
public class BuildingUpdateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 校验权限
        if (!PowerCheck.isManager(request)) {
            request.setAttribute("reMessage", "无权访问");
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return;
        }
        Integer buildingID = Integer.parseInt(request.getParameter("id"));
        List<buildings> building = new housemanageDao().findById(buildingID);
        request.setAttribute("building", building);
        request.getRequestDispatcher("/buildingmanage/buildingUpdata.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 校验权限
        if (!PowerCheck.isManager(req)) {
            req.setAttribute("reMessage", "无权访问");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        Integer buildingID = Integer.parseInt(req.getParameter("buildingID"));
        String buildingName = req.getParameter("buildingName");
        String address  = req.getParameter("address");
        int totalrooms = Integer.parseInt(req.getParameter("totalrooms"));
        int affectrows=new housemanageDao().update(buildingID,buildingName,address,totalrooms);
        if (affectrows > 0) {
            resp.getWriter().println("<script> alert('更新成功'); location.href='buildingList';</script>");
        } else if (affectrows == -1) {
            resp.getWriter().println("<script> alert('更新失败，存在重复的楼宇名称'); </script>");
        } else {
            resp.getWriter().println("<script> alert('更新失败'); </script>");
        }
    }
}
